<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { addBodyAPI, editBodyAPI } from "@/api/resource.ts";

const id = ref('')
const type = ref()
const dialogVisible = ref(false)
const ruleForm = reactive({
  name: '',
  nickname: '',
  imgUrl: ''
})
const emit = defineEmits(['get'])

// 初始
const init = (row: any, number: number) => {
  dialogVisible.value = true
  type.value = number
  ruleForm.name = ''
  ruleForm.nickname = ''
  ruleForm.imgUrl = ''
  if (number) {
    id.value = row._id
    ruleForm.name = row.name
    ruleForm.nickname = row.nickname
    ruleForm.imgUrl = row.imgUrl
  }
}

// 取消
const handleCancel = () => {
  dialogVisible.value = false
}

// 添加部位
const handleAdd = async () => {
  const res: any = await addBodyAPI(ruleForm)
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: res.message
    })
  }
  emit('get')
  handleCancel()
}

// 编辑部位
const handleEdit = async () => {
  const res: any = await editBodyAPI(id.value, ruleForm)
  ElMessage({
    type: res.code === 0 ? "success" : "error",
    message: res.message
  })
  emit('get')
  handleCancel()
}

// 上传部位图片成功回调
const onSuccessUpload = async (response: any) => {
  ruleForm.imgUrl = response.data
}

defineExpose({
  init
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="type === 0 ? '添加部位' : '编辑部位'">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      style="padding: 0 50px"
      class="demo-ruleForm"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name" type="text" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="昵称" prop="checkPass">
        <el-input v-model="ruleForm.nickname" type="text" autocomplete="off"/>
      </el-form-item>
    </el-form>
    <el-upload
      class="upload-demo"
      drag
      :on-success="onSuccessUpload"
      action="http://116.62.147.119:3636/api/uploadBody"
    >
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">
        点击这里 <em>上传</em>
      </div>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="type === 0" type="primary" @click="handleAdd">
          确定
        </el-button>
        <el-button v-else type="primary" @click="handleEdit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
